import $AppConfig from "../dev/app_config.js";
import appColumn from "../dev/vue/app-column.vue";
import loadingUI from "../dev/vue/plugin/loading";
import alertUI from "../dev/vue/plugin/alert";
import crop from "../dev/vue/directive/crop";
import $api from "../dev/vue/api";
import Cropper from "cropperjs";

import AlloyLever from "alloylever";
AlloyLever.config({
    entry: "#diploma" //请点击这个DOM元素6次召唤vConsole。//你可以通过AlloyLever.entry('#entry2')设置多个机关入口召唤神龙
});


if (window.Vue) {
    Vue.use($AppConfig, {});
    Vue.use(alertUI);
    Vue.use(loadingUI);
    Vue.directive(crop);
    Vue.component(appColumn.name, appColumn);

    var vm = new Vue({
        el: "#diploma",
        data: {
            inApp: Vue.$AppConfig.inApp,
            tavelt: 0, // 出行次数
            kilometre: 0, // 公里数
            qrCode: "",
            base64: "",
            currentDate: new Date().format("YYYY年MM月dd日"),
            share: false,
            option: {
                pic_width: 200,
                pic_height: 200,
                size: 2 * 1024 * 1024
            },
            star: Object,
            openTime: null,
            croppable: false,
            cropper: null,
            access_token: Vue.$AppConfig.getToken,
            shareState: true,
            isImg: true
        },
        methods: {
            //判断是否是微信浏览器的函数
            isWeiXin() {
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == "micromessenger") {
                    return true;
                } else {
                    return false;
                }
            },
            ajaxData() {
                // ajax 提交
                let body = {access_token: this.access_token};
                this.$http.get(Vue.$AppConfig.INTERFACE_HOST + "/findCertOrdersInfo", {params: body}, {emulateJSON: true})
                    .then(response => {
                            let body = response.body;
                            if (body.success) {
                                this.$loading.hide();
                                if (body.data.length > 0) {
                                    if ((new Date() - this.openTime) / 1000 > 1) {
                                        this.loadingDataShow(body.data[0]);
                                    } else {
                                        setTimeout(() => {
                                            this.loadingDataShow(body.data[0]);
                                        }, 1000);
                                    }
                                } else {
                                    // 弹窗提示错
                                    console.log("data数据：", body.data);
                                }
                            } else {
                                // 弹窗提示错误
                                this.$alert.text(body.text);
                                this.$loading.hide();
                            }
                        },
                        () => {
                            // 请求失败
                            this.$loading.hide();
                            this.$alert.text("网络连接失败，请稍后重试");
                        }
                    );
            },
            loadingDataShow(data) {
                this.$loading.hide();
                this.domAnimation();
                // 更行数值
                anime({
                    targets: this.$data,
                    tavelt: data.orderAmount,
                    kilometre: data.orderMilage,
                    round: 1,
                    easing: "linear",
                    duration: function () {
                        let num = data.orderAmount > data.orderMilage ? data.orderAmount : data.orderMilage;
                        return num / 1000 > 1 ? 3000 : 1500;
                    }
                });
                this.currentDate = data.currentDate;
                this.qrCode = data.shareUrl;
            },
            shareClick() {
                this.$loading.show();
                this.shareState = false;
                // 生成图片
                this.$nextTick(() => {
                    this.createdCertificate();
                });
            },
            createdCertificate(item) {
                return this.drawCanvas("#diploma");
            },
            redadDPR() {
                // 根据window.devicePixelRatio获取像素比
                if (window.devicePixelRatio && window.devicePixelRatio > 1) {
                    return window.devicePixelRatio;
                }
                return 1;
            },
            parseValue(value) {
                return parseInt(value, 10);
            },
            drawCanvas(selector) {
                // 获取canvas
                // 获取想要转换的 DOM 节点
                const dom = document.querySelector(selector);
                const box = window.getComputedStyle(dom);

                // DOM 节点计算后宽高
                const width = this.parseValue(box.width);
                const height = this.parseValue(box.height);

                // 获取像素比
                const scaleBy = this.redadDPR();
                // 创建自定义 canvas 元素
                const canvas = document.createElement("canvas");

                // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
                // canvas.width = width * scaleBy;
                // canvas.height = height * scaleBy;

                canvas.width = width;
                canvas.height = height;

                // 设定 canvas css宽高为 DOM 节点宽高
                canvas.style.width = `${width}px`;
                canvas.style.height = `s${height}px`;
                // 获取画笔
                const context = canvas.getContext("2d");

                // 将所有绘制内容放大像素比倍
                // context.scale(scaleBy, scaleBy);

                // 将自定义 canvas 作为配置项传入，开始绘制
                // scale: 1
                html2canvas(dom, {canvas: canvas, async: true}).then(canvas => {
                    this.imgUpSever(canvas.toDataURL("image/jpeg"), "diploma");
                });
            },
            imgUpSever(data, fileName) {
                this.shareState = true;
                this.$loading.hide();
                // 图片 传递给APP客户端
                if (this.inApp) {
                    // base64上传服务器

                    // let url = "http://192.168.0.103:9001/selfdriving/api";
                    this.$http({
                        url: `${Vue.$AppConfig.INTERFACE_HOST}/upload`,
                        // url: `${url}/upload`,
                        method: "post",
                        emulateJSON: true,
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded",
                            Authorization: this.access_token
                        },
                        body: {
                            access_token: this.access_token,
                            base64: data.substring(data.indexOf(',') + 1)
                        }
                    }).then(
                        function (res) {
                            let body = res.body;
                            if (body.success) {
                                this.shareShow(body.data);
                            } else {
                                this.$alert.text(body.text);
                            }
                        },
                        function (e) {
                            // 请求失败回调
                            this.$alert.text(
                                "网络连接失败，请稍后再试!"
                            );
                        }
                    );

                } else {
                    console.log(data);
                }
            },
            shareShow(url) {
                // 判断路径是否https的，是则替换
                url = url.replace('http:', 'https:');
                // 判断是否IOS
                if (Vue.$AppConfig.appJSBridge('shareCertificate', url)) {
                } else {
                    console.log("分享失败!");
                }
                // if (Vue.$AppConfig.isIos) {
                //     window.webkit.messageHandlers.shareCertificate.postMessage(url);
                // } else {
                //     window.JsBridge.shareCertificate(url);
                // }
            },
            domAnimation() {
                this.star = anime({
                    targets: this.$refs["star"],
                    scale: [1.5, 1],
                    opacity: [0, 1],
                    duration: 500,
                    delay: 500,
                    rotate: {
                        value: "1turn",
                        delay: 1000,
                        duration: 3000
                    }
                });
            },
            readImage(el) {
                this.$loading.show();
                if (el.target.files ? "" == el.target.files[0].type : /image\/(jpeg|png|gif|bmp|tiff)/.test(el.target.files[0].type)) {
                    this.$loading.hide();
                    this.$alert.text(
                        "请上传正确格式的图片, 仅支持[jpeg,png,gif,bmp,tiff)格式的图片!"
                    );
                    this.cropCancel();
                    return false;
                }

                // if (el.target.files[0].size > this.option.size) {
                //     this.$alert.text("上传图片大于2M,请重新选择上传");
                //     this.cropCancel();
                //     return false;
                // }

                // 读取图片
                this.getImage(el.target.files[0]);
            },
            getImage(source) {
                if (typeof FileReader == "undefined") return false;
                //用FileReader读取file
                var reader = new FileReader();
                reader.onload = e => {
                    this.crop(e.target.result);
                };
                reader.readAsDataURL(source);
            },

            cropClick(el) {
                if (Vue.$AppConfig.inApp) {
                    // el.target.value = "";
                    if (Vue.$AppConfig.appJSBridge('cropper')) {

                    } else {
                        console.log("裁图调用失败");
                    }
                }
            },
            cropChange(url) {
                // this.$alert.text(url);
                this.base64 = null;
                this.$nextTick(() => {
                    this.base64 = url;
                })
            },
            crop(img) {
                this.croppable = true;
                this.$nextTick(() => {
                    if (!this.cropper) {
                        // 初始化裁剪
                        var image = this.$refs.cropImg;
                        this.cropper = new Cropper(image, {
                            setDragMode: "move",
                            aspectRatio: 1,
                            viewMode: 1,
                            background: false,
                            dragMode: "none",
                            // cropBoxMovable: false,
                            cropBoxResizable: false,
                            minCropBoxWidth: 100,
                            minCropBoxHeight: 100,
                            toggleDragModeOnDblclick: false,
                            ready: () => {
                                this.croppable = true;
                                let canvas = this.cropper.getContainerData();
                                let width = canvas.width / 2 - this.option.pic_width / 2;
                                let height = canvas.height / 2 - this.option.pic_height / 2;
                                this.cropper.setCropBoxData({
                                    left: width,
                                    top: height,
                                    width: this.option.pic_width,
                                    height: this.option.pic_height
                                });
                            }
                        });
                    }
                    // this.cropper.reset().replace(img);
                    this.cropper.replace(img);
                });
            },
            cropEnlarge() {
                // 放大
                this.cropper.zoom(0.1);
            },
            cropNarrow() {
                // 缩小
                this.cropper.zoom(-0.1);
            },
            cropRotate() {
                // 旋转
                this.cropper.rotate(-90);
            },
            cropChoice() {
                // 确定
                this.base64 = "";
                this.$nextTick(() => {
                    this.base64 = this.cropper
                        .getCroppedCanvas({
                            width: this.option.pic_width,
                            height: this.option.pic_height
                        })
                        .toDataURL("image/jpeg");
                    this.cropCancel();
                });
            },
            cropCancel() {
                // 取消
                this.croppable = false;
                if (this.cropper) this.cropper.destroy();
                this.cropper = null;
                this.$loading.hide();
            }
        },
        mounted() {
            this.openTime = new Date();
            this.$nextTick(() => {
                Vue.use($api, vm);
            });
            if (!this.inApp) {
                this.$loading.hide();
                return this.$alert.text("请在APP内打开");
            }
            this.ajaxData();
        },
        created() {
            this.$loading.show();
            try {
                document.body.removeChild(document.getElementById("loading"));
            } catch (e) {
            }
        }
    });
}
